/*
 * @Author: wangjq4214
 * @Date: 2022-04-17 22:57:22
 * @LastEditTime: 2022-05-24 21:22:27
 * @LastEditors: wangjq4214
 */
package main

import (
	"context"
	"log"
	"time"

	pb "gitee.com/wangjq4214/schedule/proto/follower"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func CommitTask(addr string, task *Task) error {
	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Printf("did not connect: %v", err)
		return err
	}
	defer conn.Close()
	c := pb.NewFollowerServeClient(conn)

	// Contact the server and print out its response.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	res, err := c.CommitTask(ctx, &pb.CommitTaskReq{
		ID:      task.UUID,
		CPU:     int32(task.CPU),
		Storage: int32(task.Storage),
		Time:    task.Time,
		Need:    task.Need,
		Position: &pb.DataPosition{
			ID: task.Position.ID,
			IP: task.Position.IP,
		},
	})
	if err != nil {
		log.Printf("could not send: %v", err)
		return err
	}
	log.Printf("Msg: %s", res.GetStatus().GetMsg())
	return nil
}
